<template>
    <div class="copyEntry">
        <!-- 复制 -->
        <el-dialog title="关联" :visible.sync="dialogVisible" width="95%" top="5vh" custom-class="import-dialog" :close-on-click-modal="false">
            <div class="content" v-loading="Loading">
                <!--<div class="leftContent">
                    <HeaderTitle>
                        <div slot="title">产品信息</div> 
                    </HeaderTitle>
                    <div class="leftContent-product">
                        <el-input placeholder="产品代码/名称" v-model="filterText" size="mini"></el-input>
                        <el-tree
                            class="filter-tree"
                            :data="treeData"
                            :props="defaultProps"
                            default-expand-all
                            :expand-on-click-node="false"
                            :filter-node-method="filterNode"
                            highlight-current
                            ref="tree"
                            style="margin-top: 5px"
                            @node-click="handleNodeClick"
                        >
                            <span slot-scope="{ node }">
                                <span :title="node.label">{{ node.label }}</span>
                            </span>
                        </el-tree>
                    </div>
                    <HeaderTitle>
                        <div slot="title">规则分类</div>
                    </HeaderTitle>
                    <yh-tree
                        class="filter-tree1"
                        :data="treeTypeData"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        default-expand-all
                        highlight-current
                        ref="tree1"
                        @node-click="handleTypeClick"
                    >
                        <span slot-scope="{ node }">
                            <span :title="node.label">{{ node.label }}</span>
                        </span>
                    </yh-tree>
                </div> -->
                <div class="rightContent">
                    <HeaderTitle>
                        <div slot="title">规则列表</div>
                    </HeaderTitle>
                    <div class="right-input">
                        <div class="hdSupport">
                            <el-form label-width="90px">
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="条款原文：" v-if="['1', '2'].includes(treeNodeData.indexType)">
                                            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 2 }" placeholder="请输入内容" v-model="hdSupport.clauseText"> </el-input>      
                                        </el-form-item>
                                        <el-form-item label="制度条款：" v-if="treeNodeData.indexType == '3'">
                                            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 2 }" placeholder="请输入内容" v-model="hdSupport.institutionalProvisions"> </el-input>      
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="6">
                                        <el-form-item label="事后系统支持情况：" label-width="140px">
                                            <el-select v-model="hdSupport.hdSupport" size="mini" clearable @change="changeHdSupport">
                                                <el-option value="1" :key="1" label="支持"></el-option>
                                                <el-option value="2" :key="2" label="部分支持"></el-option>
                                                <el-option value="3" :key="3" label="不支持"></el-option>
                                            </el-select>      
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="9">
                                        <el-form-item label="不可配置说明：" v-show="['2', '3'].includes(hdSupport.hdSupport)" label-width="120px">
                                            <el-input placeholder="请输入内容" v-model="hdSupport.unconfigurableDescription" size="mini" style="width: 100%"> </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="9">
                                        <el-form-item label="注意事项：" v-show="['2', '3'].includes(hdSupport.hdSupport)">
                                            <el-input placeholder="请输入内容" v-model="hdSupport.cautions" size="mini" style="width: 100%"> </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="8">
                                        <el-input v-model="selectData.entryNameLike" placeholder="请输入规则编号或说明" size="small" style="width: 300px"> </el-input>
                                        <el-button type="primary" @click="getRiskEntry(paging, sorter, selectData)" size="mini">查询</el-button>
                                    </el-col>
                                </el-row>   
                            </el-form>
                        </div>
                    </div>
                    <div style="position: relative">
                        <el-table
                            :data="tableData"
                            tooltip-effect="dark"
                            style="width: 99%; margin: 0 auto"
                            border
                            ref="table"
                            size="mini"
                            height="380px"
                            :auto-resize="true"
                            v-loading="tabloading"
                            @sort-change="handleSort"
                            :default-sort="{ prop: sortProp, order: sortOrder }"
                        >
                            <RiskTableSelection
                                row-key="entryCode"
                                :current-page-table-list="tableData"
                                :selected="selectedList"
                                show-drop-down
                                width="60"
                            />
                            <!-- <el-table-column type="selection" width="55"></el-table-column> -->
                            <el-table-column label="规则编号" width="120" prop="entryCode" fixed="left" sortable="custom" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span v-if="scope.row.modifyType === '2' && scope.row.modifyStatus === '1'">
                                        <i class="el-icon-setting" />{{ scope.row.entryCode }}
                                    </span>
                                    <span v-else-if="scope.row.modifyType === '3' && scope.row.modifyStatus === '1'">
                                        <i class="el-icon-delete" />{{ scope.row.entryCode }}
                                    </span>
                                    <span v-else-if="scope.row.modifyType === '1' && scope.row.modifyStatus === '1'">
                                        <i class="el-icon-folder-add" />{{ scope.row.entryCode }}
                                    </span>
                                    <span v-else>
                                        {{ scope.row.entryCode }}
                                    </span>
                                </template>
                            </el-table-column>

                            <el-table-column
                                v-for="(col, index) in Columns"
                                :key="index"
                                :prop="col.prop"
                                :label="col.title"
                                :width="col.width"
                                :min-width="col.minWidth || '105px'"
                                show-overflow-tooltip
                                :sortable="col.sortable ? 'custom' : false"
                            >
                                <template slot-scope="scope">
                                    <span v-if="['thresholdValue1', 'thresholdValue2', 'thresholdValue3'].includes(col.prop)" style="float: right">
                                        {{ scope.row[col.prop] ? thresholdTypeFormat(scope.row[col.prop], scope.row.unit) : '' }}
                                    </span>

                                    <span v-else-if="col.prop === 'entryName'" @click="handleRowClick(scope.row)" class="text-hover">
                                        {{ scope.row[col.prop] }}
                                    </span>

                                    <span v-else v-html="getTbalesData(scope.row, col.prop)"></span>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="paging" @page-change="pageRet"></risk-pagination>
                        </div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="sendBatchAddRelations">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator';
import HeaderTitle from '../commom/header-title.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { UUID, timeFormat, numberFormat, unitShow } from '@/utils/tools';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'CopyEntryDialog',
    components: {
        HeaderTitle,
        RiskIconButton,
        RiskPagination,
    },
})
export default class CopyEntryDialog extends Vue {
    @Prop() copyEntryDialog;
    @Prop() indexClauseRelation; // 当前点击的条款
    @Prop() clauseCodesList; // 条款多选全部数据
    @Prop() relaCopy;
    @Prop() treeNodeData;
    @Prop() indexClauseRelationList;
    @Prop() Type;

    private dialogVisible: boolean = false;
    accountList: any[] = [];
    // treeData: any[] = [
    //     // 条目列表
    //     {
    //         id: '-1',
    //         label: '全部选择',
    //         children: [],
    //     },
    // ];
    // treeTypeData: any[] = [
    //     // 风险类别
    //     {
    //         id: '-1',
    //         label: '全部选择',
    //         children: [],
    //     },
    // ];
    paging: any = {
        total: 0,
        currentPage: 1,
        totalPage: 0,
        pageSize: 25,
    };
    sorter: any = {
        entryCode: 'descend',
    };
    sortProp: string = 'entryName';
    sortOrder: string = 'desc'; // 排序方式
    tabloading: boolean = false;
    multipleSelection = []; // 多选
    batchAddRelations = []; // 关联字段
    selectData: any = {
        entryCode: [], // 条目编号
        precision: false, // 准确搜索
        riskCalTypes: [], // 作用范围
        entryName: '', // 风险说明
        entryStatuss: [], // 启用状态
        controlGrades: [], // 风险等级
        beginDate: '', // 生效时间
        endDate: '', // 失效时间
        accountControlValue: [], // 基金账户
        sourceType: [], // 条目来源
        riskTypes: [], // 风险类型
        entryGroups: [], // 条目组
        excludeEntryGroup: false, // 排除选中
        customType: [], // 自定义分类
        checkUserCodes: '', // 复核人
        checkTableDataDirection: '', // 复核时间
        entryRoleCode: [], // 条目角色
        sort: '', // 排序字段
        fdAcCodeControlValue: [],
        assetCodeControlValue: [],
        entryNameLike: '', // 模糊查询
        displayedPremise: true, // 不展示前提条目内容
        fdProductCode: '', // 根据所选择的产品下的条款，在点击条目关联时，自动带入当前产品下的条目进行展示条目
        clauseCode: '',
    };
    prams: any = {
        accountControlValue: [],
        riskTypes: [],
        sourceType: [],
    };
    filterText = '';
    defaultProps = {
        children: 'children',
        label: 'label',
    };
    tableData: any[] = [];
    private groupPage: pages = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    // 排序字段
    sortParamObj = {
        entryName: 'C_ENTRY_NAME',
    };
    Columns: any[] = [
        {
            title: '风险说明',
            prop: 'entryName',
            minWidth: 250,
            tooltip: false,
            sortable: true,
        },
        {
            title: '变动序号',
            prop: 'changeNo',
            tooltip: false,
        },
        {
            title: '风险类型',
            prop: 'riskType',
            minWidth: 130,
            tooltip: false,
        },
        {
            title: '生效日期',
            prop: 'beginDate',
        },
        {
            title: '失效日期',
            prop: 'endDate',
        },
        {
            title: '优先级',
            prop: 'level',
        },
        {
            title: '状态',
            prop: 'entryStatusValid',
        },
        {
            title: '风险等级',
            prop: 'controlGrade',
        },
        {
            title: '作用范围',
            prop: 'riskCalTypes',
        },
        {
            title: '阈值类型1',
            prop: 'thresholdType1',
            minWidth: 120,
        },
        {
            title: '阈值1',
            prop: 'thresholdValue1',
            minWidth: 150,
            funcBody: (value, record) => (value ? this.thresholdTypeFormat(value, record.unit) : ''),
        },
        {
            title: '阈值类型2',
            prop: 'thresholdType2',
            minWidth: 120,
        },
        {
            title: '阈值2',
            prop: 'thresholdValue2',
            minWidth: 150,
            funcBody: (value, record) => (value ? this.thresholdTypeFormat(value, record.unit) : ''),
        },
        {
            title: '阈值类型3',
            prop: 'thresholdType3',
            minWidth: 120,
        },
        {
            title: '阈值3',
            prop: 'thresholdValue3',
            minWidth: 150,
            funcBody: (value, record) => (value ? this.thresholdTypeFormat(value, record.unit) : ''),
        },
        {
            title: '比较方向',
            prop: 'compareType',
        },
        {
            title: '账户层次',
            prop: 'originalAccoutId',
            minWidth: 150,
        },
        {
            title: '控制类型',
            prop: 'accountControlType',
            minWidth: 150,
        },
        {
            title: '控制账户',
            prop: 'accountControlValue',
            minWidth: 150,
        },
        {
            title: '排除账户',
            prop: 'accountDebarValue',
            minWidth: 120,
        },
        {
            title: '排除账户组',
            prop: 'accountGroupDebarValue',
            minWidth: 150,
        },

        {
            title: '修改日期',
            prop: 'modifyDate',
        },
        {
            title: '修改时间',
            prop: 'modifyTime',
        },
        {
            title: '修改人',
            prop: 'modifyUser',
            minWidth: 150,
        },
        {
            title: '规则来源',
            prop: 'sourceType',
        },
        {
            title: '自定义分类',
            prop: 'customType',
            minWidth: 140,
        },
        {
            title: '规则角色分类',
            prop: 'entryRoleCode',
            minWidth: 180,
            tooltip: false,
        },
    ];
    selectedList: any[] = [];
    selectedItem = [];
    allSelectedItem = [];
    Loading = false;
    @Watch('copyEntryDialog')
    watchCopyEntryDialog(val) {
        this.dialogVisible = val;
        if (val == true) {
            if (this.treeNodeData.indexType == '2') {
                this.selectData.fdProductCode = this.indexClauseRelation.productCode ? this.indexClauseRelation.productCode : this.indexClauseRelation.clauseCode.productCode;
            } else {
                this.selectData.fdProductCode = '';
            }
            this.selectData.clauseCode = this.indexClauseRelation.clauseCode;
            this.Loading = true;
            this.getAllData();
            this.getDetailData(this.indexClauseRelation.clauseCode)
        }
    }
    @Watch('dialogVisible')
    watchDialogVisible(val) {
        if (val == false) {
            this.selectedItem = [];
            this.selectedList = [];
            this.paging = {
                total: 0,
                currentPage: 1,
                totalPage: 0,
                pageSize: 25,
            };
            this.hdSupport = { 
                clauseText: '',
                hdSupport: '',
                institutionalProvisions: '',
                configurableDescription: '',
                unconfigurableDescription: '',
                cautions: '',
            };
            this.$emit('emitCopyEntryDialog', val, '');
        }
    }
    @Watch('selectedList')
    watchSelectedList(val, oldVal) {
        let arr = [];
        for (let i = this.tableData.length - 1; i >= 0; i--) {
            if (val.includes(this.tableData[i].entryCode)) {
                arr.push(this.tableData[i]); // 获取勾选条目所有字段数据
                this.tableData.splice(i, 1)
            }
        }
        arr.forEach(item => {
            this.allSelectedItem.push(item); // 存跨页数据
        })
        this.allSelectedItem = this.screenProductList(this.allSelectedItem, 'entryCode');
        for (var i = this.allSelectedItem.length - 1; i >= 0; i--) {
            if (!val.includes(this.allSelectedItem[i].entryCode)) {
                this.allSelectedItem.splice(i, 1);
            }
        }
        this.selectedItem = []
        this.allSelectedItem.forEach(item => {
            if (val.includes(item.entryCode)) {
                this.selectedItem.push(item)
            }
        })
        this.selectedItem = this.screenProductList(this.selectedItem, 'entryCode');

        this.selectedItem.forEach(item => {
            this.tableData.unshift(item);
        })
    }

    customTypesList: any[] = [];
    cutomTypes: any = null;
    fundGroups: any[] = [];
    funds: any[] = [];
    fundPojo: any = {};
    fundGroupPojo: any = {};
    dom = null;
    hdSupport = { // 事后系统支持情况
        clauseText: '',
        institutionalProvisions: '',
        hdSupport: '',
        configurableDescription: '',
        unconfigurableDescription: '',
        cautions: ''
    }
    clauseDetails = {
        supportText: '',
        clauseText: '',
        hdSupport: '',
        institutionalProvisions: '',
    }; // 条款详情数据

    mounted() {
        // 获取需要绑定的table
        // console.log('hzj!!', this.$refs.eltable)
        // (this.$refs.eltable as any).bodyWrapper.addEventListener('scroll', (res) => {
        //  // 滚动距离
        //  console.log('hzj!!', res)
        // })
    }
    async getAllData() {
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
        // 条目数据
        // let fubds = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
        // let local = [];
        // for (let itme of fubds) {
        //     let datas = itme.fundCode + '-' + itme.fundName;
        //     local.push({ label: datas, id: itme.fundCode });
        // }

        let fundPojo = {};
        let fundGroupPojo = {};

        // 条目组
        this.funds = (await DictionConstUtil.FNFundInfo()) || [];
        // 产品组信息
        this.fundGroups = (await DictionConstUtil.FNFundGroup()) || [];
        // 产品信息
        let funds = this.funds;
        // 产品组信息
        let fundGroups = this.fundGroups;
        funds.forEach(item => {
            fundPojo[item.fundCode] = item.fundNameSt;
        });
        fundGroups.forEach(item => {
            fundGroupPojo[item.fundGroupCode] = item.fundGroupName;
        });
        // -1 也在展示范围内
        fundPojo['-1'] = '全部选择';
        fundGroupPojo['-1'] = '全部选择';

        this.fundPojo = fundPojo;
        this.fundGroupPojo = fundGroupPojo;

        // 基金账户
        // this.accountList = local;
        // this.treeData[0].children = local;
        // 自定义风险分类
        // 自定义风险
        this.customTypesList = (await DictionConstUtil.FNCustomType()) || [];
        this.cutomTypes = DictionConstUtil.ListToPojo(this.customTypesList || []) || {};

        // 风险类别数据
        // let entryType = await SGU_CACHE('RiskType', '/entry/riskType', []);
        // let typeLocal = [];
        // for (let itme of entryType) {
        //     let datas = itme.riskTypeId + ' ' + itme.riskTypeName;
        //     typeLocal.push({ label: datas, id: itme.riskTypeId });
        // }
        // typeLocal.sort(this.compare('id'));
        // this.treeTypeData[0].children = typeLocal;
    }
    // 编辑
    getDetailData(data) {
        this.$axios.post('/zhiguan/indexClause/getClauseDetails', { clauseCode: data }).then((res: any) => {
            this.clauseDetails = {...res};
            let supportText = res.supportText != '' ? JSON.parse(res.supportText) : '';
            this.hdSupport = { 
                clauseText: res.clauseText ? res.clauseText : '',
                hdSupport: res.hdSupport ? res.hdSupport : '',
                institutionalProvisions: res.institutionalProvisions ? res.institutionalProvisions : '',
                configurableDescription: supportText != '' ? supportText[1].configurableDescription : '',
                unconfigurableDescription: supportText != '' ? supportText[1].unconfigurableDescription : '',
                cautions: supportText != '' ? supportText[1].cautions : '',
            };
            this.Loading = false;
            console.log('编辑', this.hdSupport)
        });
    }
    compare(val) {
        return function (a, b) {
            return a[val] - b[val];
        };
    }
    thresholdTypeFormat(value, unit): string {
        // 三目运算符, unit为'%'和'万元'、'万股'的由后端处理了，不由numberFormat方法处理
        return ['%', '万元', '万股'].includes(unit) ? value : numberFormat(value.replace(/[^0-9.]/gi, ''), unit) + unitShow(unit);
    }
    // 处理table中的数据
    getTbalesData(data: any, props: any) {
        // 自定义风险分类
        let datas = data[props];
        if (props == 'riskType') {
            return DictionConstUtil.EntryType[datas];
        } else if (props == 'entryStatusValid') {
            if (data[props] == true) {
                let span = '<span style="color:green">启用</span>';
                return span;
            } else {
                let span = '<span style="color:red">停用</span>';
                return span;
            }
        } else if (props == 'sourceType') {
            return DictionConstUtil.SourceType[datas];
        } else if (props == 'beginDate') {
            if (datas == '0') {
                return '';
            } else {
                return datas;
            }
        } else if (props == 'endDate') {
            if (datas == '0') {
                return '';
            } else {
                return datas;
            }
        } else if (props == 'modifyTime') {
            return timeFormat(datas);
        } else if (props == 'controlGrade') {
            return DictionConstUtil.ControlGrade[datas];
        } else if (props == 'riskCalTypes') {
            let result = '';
            for (let i = 0; i < datas.length; i++) {
                result += DictionConstUtil.RiskCalType[datas[i]] + ',';
            }
            return result;
        } else if (props == 'compareType') {
            return DictionConstUtil.CompareDirection[datas];
        } else if (props == 'originalAccoutId') {
            return DictionConstUtil.OriginalAccountType[datas];
        } else if (props == 'accountControlType') {
            return DictionConstUtil.AccountControlType[datas];
        } else if (props == 'accountControlValue') {
            if (datas && datas.length > 0) {
                if (String(data.originalAccoutId) === '0') {
                    let fundNames = datas.map(item => this.fundPojo[item]);
                    return fundNames.join(',');
                } else {
                    let fundGroupNames = datas.map(item => this.fundGroupPojo[item]);
                    return fundGroupNames.join(',');
                }
            } else {
                return datas;
            }
        } else if (props == 'accountDebarValue') {
            if (datas && datas.length > 0) {
                let fundNames = datas.map(item => this.fundPojo[item]);
                return fundNames.join(',');
            } else {
                return datas;
            }
        } else if (props == 'accountGroupDebarValue') {
            if (datas && datas.length > 0) {
                if (String(data.originalAccoutId) === '0') {
                    let fundNames = datas.map(item => this.fundPojo[item]);
                    return fundNames.join(',');
                } else {
                    let fundGroupNames = datas.map(item => this.fundGroupPojo[item]);
                    return fundGroupNames.join(',');
                }
            } else {
                return datas;
            }
        } else if (props == 'customType') {
            return this.cutomTypes[datas];
        } else if (props == 'thresholdType1' || props == 'thresholdType2' || props == 'thresholdType3') {
            return DictionConstUtil.ThresholdType[datas];
        } else if (props == 'entryRoleCode') {
            if (datas != null) {
                let entryRoleCodes = datas.split(',');
                if (entryRoleCodes.length > 0 && entryRoleCodes.length === 1) {
                    return DictionConstUtil.EntryRole[datas];
                } else {
                    let name = '';
                    for (let i = 0; i < entryRoleCodes.length; i++) {
                        name += DictionConstUtil.EntryRole[entryRoleCodes[i]] + ',';
                    }
                    return name;
                }
            }
        } else {
            return datas;
        }
    }
    // 产品查询
    handleNodeClick(val: any): void {
        this.selectData.accountControlValue = [];
        if (val.id != '-1') {
            this.selectData.accountControlValue.push(val.id);
        }
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
    }
    // 风险类别查询
    handleTypeClick(val: any): void {
        this.selectData.riskTypes = [];
        this.selectData.riskTypes.push(String(val.id));
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
    }
    // 获取条目列表
    getRiskEntry(paging: any, sorter: any, selectData: any): void {
        this.tabloading = true;
        let arr = []
        this.indexClauseRelationList.forEach(item => {
            arr.push(item.entryCode)
        })
        let URL = (this.Type == '添加关联' ? '/entry/clause/list' : '/entry/list')
        this.$axios
            .post(URL, {
                paging: paging,
                sorter: sorter,
                riskEntryControlQuery: {...selectData, filterEntryCodes: arr},
            })
            .then((res: any) => {
                res.riskEntryControls.map((item: any) => {
                    item.key = item.entryCode;
                    return item;
                });
                this.paging.total = res.count;
                this.tableData = res.riskEntryControls;
                this.tabloading = false;
                // this.onChangselectedFieldList();
                if (this.selectedItem.length > 0) {
                    for (let i = this.tableData.length - 1; i >= 0; i--) {
                        if (this.selectedList.includes(this.tableData[i].entryCode)) {
                            this.tableData.splice(i, 1)
                        }
                    }
                    this.selectedItem.forEach(item => {
                        this.tableData.unshift(item);
                    })
                }
            })
            .catch(() => {
                this.paging.total = 0;
                this.tableData = [];
                this.tabloading = false;
            });
    }
    // 分页
    private pageRet(): void {
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
    }
    // 表头排序
    handleSort(column: any) {
        this.sortProp = column.prop;
        this.sortOrder = column.order;
        const sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        let sort = '';
        const prop = column.prop;
        if (sortType) {
            if (prop == 'entryCode') {
                if (sortType == 'DESC') {
                    sort = "TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) DESC";
                } else {
                    sort = "TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) ASC";
                }
            } else {
                sort = this.sortParamObj[prop] + ' ' + sortType;
            }
        }
        this.selectData.sort = sort;
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
    }
    // 多选
    handleSelectionChange(val) {
        this.multipleSelection = val;
    }
    // 确认关联
    sendBatchAddRelations() {
        if (this.relaCopy) {
            this.copyEntry();
            return;
        }
        if (this.selectedItem.length == 0) {
            this.yh_message_warn('关联条目不可为空！');
            return;
        }
        if (this.hdSupport.hdSupport == '') {
            this.yh_message_warn('事后系统支持情况不可为空！');
            return;
        }
        this.batchAddRelations = [];
        let clauseCodeS = [];
        let entryCodeS = [];
        if (this.indexClauseRelation.modifyEvent == '1') {
            this.yh_message_warn('所选条款存在未复核！');
            return;
        }
        clauseCodeS = [this.indexClauseRelation.clauseCode];
        this.selectedItem.forEach(item => {
            entryCodeS.push(item.entryCode);
        });
        // 修改条款详情
        if (this.clauseDetails.supportText) {
            let supportText = JSON.parse(this.clauseDetails.supportText);
            supportText[1] = {
                configurableDescription: this.hdSupport.configurableDescription,
                unconfigurableDescription: this.hdSupport.unconfigurableDescription,
                cautions: this.hdSupport.cautions,
            };
            this.clauseDetails.supportText = JSON.stringify(supportText);    
        } else {
            let supportText = [
                {
                    configurableDescription: '',
                    unconfigurableDescription: '',
                    cautions: '',
                },
                {
                    configurableDescription: this.hdSupport.configurableDescription,
                    unconfigurableDescription: this.hdSupport.unconfigurableDescription,
                    cautions: this.hdSupport.cautions,
                }
            ]
            this.clauseDetails['supportText'] = JSON.stringify(supportText);
        }
        if (this.treeNodeData.indexType == '3') {
            this.clauseDetails.institutionalProvisions = this.hdSupport.institutionalProvisions;
        } else {
            this.clauseDetails.clauseText = this.hdSupport.clauseText;
        }
        this.clauseDetails.hdSupport = this.hdSupport.hdSupport;
        this.$axios
            .post('/zhiguan/indexClause/update', this.clauseDetails)
            .then((res: any) => {})
        // 关联条目
        this.$axios
            .post('/zhiguan/indexClause/addClauseEntry', {
                entryCodeSS: entryCodeS,
                clauseCodeS: clauseCodeS,
            })
            .then((res: any) => {
                this.yh_message_success('关联成功！');
                this.$emit('emitCopyEntryDialog', false, '确认关联');
                this.dialogVisible = false;
            });
    }

    copyEntry() {
        if (this.selectedItem.length == 0) {
            this.yh_message_warn('复制条目不可为空！');
            return;
        }
        if (this.selectedItem.length === 1) {
            this.$emit('handleOneCopy', this.selectedItem[0].entryCode);
            this.$emit('emitCopyEntryDialog', false, ' ');
            this.dialogVisible = false;
            return;
        }
        const entryCodes = this.selectedItem.map(i => i.entryCode);
        this.$axios.post('/entry/multiCopy', { entryCodes, clauseCode: this.indexClauseRelation.clauseCode }).then((res: any) => {
            this.yh_message_success('复制成功！ 请前往复核');
            this.$emit('emitCopyEntryDialog', false, '确认关联');
            this.dialogVisible = false;
        });
    }

    filterChangeEvent() {}
    @Watch('filterText')
    handleDataSource(val) {
        (this.$refs.tree as any).filter(val);
    }
    filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
    }

    handleRowClick(row) {
        const msg = {
            type: 'look-entry-details',
            path: `/lookEntryDetails?entryCode=${row.entryCode}`,
            title: `条目详情-${row.entryCode}`,
        };
        top.window.postMessage(msg, '*');
    }
    changeHdSupport(param) {
        if (param == '' || param == '1') {
            this.hdSupport.configurableDescription = '';
            this.hdSupport.unconfigurableDescription = '';
            this.hdSupport.cautions = '';
        }
    }
    screenProductList(arr, field) {
        // 缓存用于记录
        const cache = [];
        for (const t of arr) {
            // 检查缓存中是否已经存在
            if (cache.find(c => c[field] === t[field])) {
                // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
                continue;
            }
            // 不存在就说明以前没遇到过，把它记录下来
            cache.push(t);
        }
        // 记录结果就是过滤后的结果
        return cache;
    }
}
</script>
<style lang="scss" scoped>
.copyEntry {
    background: #ffffff;
}
.content {
    display: flex;
    // overflow: hidden;
    height: 73vh;
    .leftContent {
        width: 220px;
        height: 73vh;
        padding-right: 3px;
        border-right: 1px solid #e5e5e5;
        .leftContent-product {
            margin-top: 10px;
        }
    }
    .el-tree {
        border: 1px solid #dcdfe6;
        height: 30vh;
        overflow: auto;
        padding-top: 5px;
    }
    .rightContent {
        width: calc(100%);
    }
}
/deep/ .el-dialog .el-dialog__body {
    height: 76vh !important;
    padding: 0px 10px 10px 10px !important;
    max-height: 80vh !important;
}

.text-hover {
    cursor: pointer;

    &:hover {
        color: #518bd3;
        text-decoration: #518bd3 solid underline;
    }
}
.right-input {
    margin: 10px;
    .clauseText {
        display: flex;
        margin-bottom: 10px;
    }
    .hdSupport {
        width: 100%;
    }    
}
/deep/ .el-form-item {
    margin-bottom: 10px !important;
}
</style>
